package OBJ_Loader;

import graphic.TextureBase;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import klient.Klient;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;

/**
 *  
 * @author Marcin & Bartek
 * 
 * @description Defines algorithms for importing files with extensions .mtl
 * These files describe materials for .obj objects
 * 
 */
public final class mtlLoader {
    private mtlLoader(){}
    public static MTLObj load(String str) {
        File f=new File(str);
        MTLObj obj = new MTLObj();
        BufferedReader br;
        try{
            br = new BufferedReader(new FileReader(f));
        }catch(Exception e){
            Klient.log("Niepowodzenie: "+f.getPath());
            return null;
        }
        Klient.log("Otworzyłem "+f.getPath());
        String line;
        Material nm=null;
        int counter=0;
        try{
        while((line = br.readLine())!=null){
            ++counter;
            if(line.startsWith("newmtl")){
                if(nm!=null)
                    obj.getList().add(nm);
                nm=new Material();    
                nm.setName(line.split(" ")[1]);
                Klient.log("Materiał: "+nm.getName());
            }else if(line.startsWith("Ns")){
                nm.setNs((float) Float.valueOf(line.split(" ")[1]));
            }else if(line.startsWith("Ka")){
                nm.setAmb(new Vector3f(Float.valueOf(line.split(" ")[1]),
                           Float.valueOf(line.split(" ")[2]),
                           Float.valueOf(line.split(" ")[3])));
                if(nm.getAmb().x<0.3f) nm.getAmb().x=0.5f;
                if(nm.getAmb().y<0.3f) nm.getAmb().y=0.5f;
                if(nm.getAmb().z<0.3f) nm.getAmb().z=0.5f;
            }else if(line.startsWith("Kd")){
                nm.setDiff(new Vector3f(Float.valueOf(line.split(" ")[1]),
                           Float.valueOf(line.split(" ")[2]),
                           Float.valueOf(line.split(" ")[3])));
            }else if(line.startsWith("Ks")){
                nm.setSpec(new Vector3f(Float.valueOf(line.split(" ")[1]),
                           Float.valueOf(line.split(" ")[2]),
                           Float.valueOf(line.split(" ")[3])));
            }else if(line.startsWith("d")){
                nm.setNs((float) Float.valueOf(line.split(" ")[1]));
            }else if(line.startsWith("map_Kd")){
                nm.setTex(TextureBase.get("images/"+f.getName().split("\\.")[0]+"/"+line.split(" ")[1]));
            }
        }
        if(nm!=null)
            obj.getList().add(nm);
        br.close();
        }catch(Exception e){
            Klient.log("Błąd pliku: "+f.getPath()+" w linii "+counter);
            return null;
        }
        return obj;
    }
    
}
